package fr.insee.rome.io.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.Proxy;
import java.util.Set;

import fr.insee.rome.Rome;
import fr.insee.rome.bean.Metier;
import fr.insee.rome.factory.RomeFactory;
import fr.insee.rome.io.reader.DomainesReader;
import fr.insee.rome.io.reader.MetierReader;
import fr.insee.rome.io.reader.ResultatsReader;
import fr.insee.rome.io.reader.TxtDomainesReader;
import fr.insee.rome.io.writer.CsvRomeWriter;
import fr.insee.rome.io.writer.RomeWriter;

public class HttpRomeDownloader implements RomeDownloader{

	private static RomeDownloader instance = null;
	
	private HttpRomeDownloader(){}
	
	public static RomeDownloader getInstance(){
		if(instance == null){
			instance = new HttpRomeDownloader();
		}
		return instance;
	}
	
	public void download() throws IOException {
		
		DomainesReader domaines = TxtDomainesReader.getInstance();
		RomeWriter writer = CsvRomeWriter.getInstance();
		
		domaines.open("./txt/domaines.txt");
		writer.open("./txt/metiers.csv");
		
		for (String domaine : domaines) {
			
			/*
			SocketAddress socket = new InetSocketAddress(
				"proxy-orange.http.insee.fr",
				8080
			);
			Proxy proxy = new Proxy(Proxy.Type.HTTP, socket);
			*/
			Proxy proxy = Proxy.NO_PROXY;		
			
			RomeRequest request = RomeFactory.getRequest(proxy);
			request.retrieveSessionId(Rome.urlIndex);
			request.setParameter("domaineNicolaId", domaine);
			request.setParameter("typeAffichageRome", "arbo");
			InputStream stream = null;
			
			stream = request.doPost(Rome.urlArbo);
		
			ResultatsReader resultatsReader = RomeFactory.getResultatsReader();
			int resultats = resultatsReader.read(stream);
			
			System.out.println(domaine);
			
			for(int n = 0 ; n < resultats + 20 ; n = n + 20){
				
				stream = request.doPost(Rome.urlSuivant + "?countElemList=" + n);
				
				MetierReader metierReader = RomeFactory.getMetierReader();
				Set<Metier> metiers = metierReader.read(stream);

				writer.write(metiers);

				stream.close();
				stream = null;
			}
		}
		
		domaines.close();
		writer.close();
	}

}
